package admin

import (
	"laohuo/dao"
	"laohuo/model"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

type Sku struct{}

func (c *Sku) List(ctx *gin.Context) {
	params := &struct {
		Page     uint
		Pagesize uint
	}{}
	ctx.ShouldBindQuery(params)
	if params.Page == 0 {
		params.Page = 1
	}
	if params.Pagesize == 0 || params.Pagesize > 100 {
		params.Pagesize = 20
	}

	sus, err := dao.FetchSku(params.Page, params.Pagesize)
	if err != nil {
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}

	total, _ := dao.CountSku()
	ctx.JSON(http.StatusOK, struct {
		Total int
		Data  []*model.SKU
	}{total, sus})
}

func (c *Sku) Add(ctx *gin.Context) {
	params := &model.SKU{}
	if err := ctx.ShouldBindJSON(params); err != nil {
		ctx.String(http.StatusBadRequest, err.Error())
		return
	}
	if params.Name == "" || params.WareId == 0 {
		ctx.String(http.StatusBadRequest, "参数错误")
		return
	}

	if _, err := dao.FetchWareById(params.WareId); err != nil {
		ctx.String(http.StatusBadRequest, err.Error())
		return
	}

	params.Time = uint(time.Now().Unix())
	if err := dao.AddSKU(params); err != nil {
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.JSON(http.StatusOK, params)
}
